# -*- coding: utf-8 -*-
import json
import logging
from datetime import timedelta

from common.campaign.db.daily_bet_return import set_daily_bet
from common.campaign.model.daily_bet_return import DAILY_BET_GAME_TYPE
from common.lottery.db import generate_track_detail
from common.lottery.model import TrackIndex
from common.preset.db.banner import get_banner_by_type
from common.preset.model.preset import BANNER_TYPE
from common.stats import MG_BIGBANG_COLL
from common.utils.tz import now_ts, today_str, local_now, get_utc_date

_LOGGER = logging.getLogger('bigbang')


def get_campaign_status(user_id):
    banner = get_banner_by_type(BANNER_TYPE.DAILY_BET)
    if not banner:
        return {
            'status': 'not_available',
        }
    if now_ts() > banner.campaign_end:
        return {
            'status': 'ended',
        }
    if now_ts() < banner.campaign_start:
        return {
            'status': 'not_started',
            'left_seconds': banner.campaign_start - now_ts()
        }
    if banner.start_ts <= now_ts() <= banner.campaign_end:
        return {
            'status': 'ongoing',
            'lottery_amount': _get_lottery_amount(user_id),
            'casino_amount': _get_casino_amount(user_id)
        }


def _get_lottery_amount(user_id):
    user_data = MG_BIGBANG_COLL.daily_stats.find_one({'_id': '%s-%s' % (user_id, today_str())})
    if not user_data:
        return 0
    amount = float(user_data.get('pay', {'total': 0}).get('total', 0))
    coupon = float(user_data.get('coupon', {'use': 0}).get('use', 0))
    real_amount = round(amount - coupon, 2)
    real_amount -= _get_track_amount(user_id)
    set_daily_bet(user_id, DAILY_BET_GAME_TYPE.LOTTERY, real_amount, today_str())
    return real_amount


def _get_track_amount(user_id):
    tomorrow_sir = (local_now() + timedelta(days=1)).strftime('%Y-%m-%d')
    start_date = get_utc_date(local_now().strftime('%Y-%m-%d'))
    end_date = get_utc_date(tomorrow_sir)
    track_in_today_query = TrackIndex.query. \
        filter(TrackIndex.user_id == user_id). \
        filter(TrackIndex.created_at > start_date). \
        filter(TrackIndex.created_at < end_date). \
        all()
    track_amount = 0
    for track_index in track_in_today_query:
        try:
            detail_data = json.loads(track_index.detail)
            if float(detail_data.get('total_amount', 0)) == 0:
                new_track_index = generate_track_detail(track_index.track_id)
                detail_data = json.loads(new_track_index.detail)
            # 临时把追号的流水全去掉，活动说明已经这么定了，后面会改成注释的功能
            # amount = float(detail_data.get('total_amount', 0)) - float(detail_data.get('bet_amount', 0))
            amount = float(detail_data.get('total_amount', 0))
            track_amount += amount if amount > 0 else 0
        except Exception as e:
            _LOGGER.error(e)
    return track_amount


def _get_casino_amount(user_id):
    user_data = MG_BIGBANG_COLL.daily_stats.find_one({'_id': '%s-%s' % (user_id, today_str())})
    if not user_data:
        return 0
    kfc_amount = float(user_data.get('kfc', {'bet_amount': 0}).get('bet_amount', 0))
    lottery_amount = float(user_data.get('lottery', {'bet_amount': 0}).get('bet_amount', 0))
    bull_amount = float(user_data.get('bull', {'bet_amount': 0}).get('bet_amount', 0))
    fruit_amount = float(user_data.get('fruit', {'bet_amount': 0}).get('bet_amount', 0))
    casino_amount = round(lottery_amount + bull_amount + kfc_amount + fruit_amount, 2)
    set_daily_bet(user_id, DAILY_BET_GAME_TYPE.CASINO, casino_amount, today_str())
    return casino_amount
